import App from '@/App.vue';

import Components from '@/components';
import Plugins from '@/plugins';
import {ROUTERS} from '@/routers';
import store from '@/store';
import MenuUtil from '@/utils/menu';
import UserUtil from '@/utils/user';
import {library} from '@fortawesome/fontawesome-svg-core';
import {fab} from '@fortawesome/free-brands-svg-icons';
import {far} from '@fortawesome/free-regular-svg-icons';
import {fas} from '@fortawesome/free-solid-svg-icons';
import {FontAwesomeIcon, FontAwesomeLayers, FontAwesomeLayersText} from '@fortawesome/vue-fontawesome';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/heatmap';
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/dataZoom';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/timeline';
import 'echarts/lib/component/title';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/visualMap';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import QrcodeVue from 'qrcode.vue';
import 'quill/dist/quill.bubble.css';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import Vue from 'vue';
import VueRouter, {RouteConfig} from 'vue-router';

library.add(fas, far, fab);

Vue.component('font-awesome-icon', FontAwesomeIcon);
Vue.component('font-awesome-layers', FontAwesomeLayers);
Vue.component('font-awesome-layers-text', FontAwesomeLayersText);

Vue.config.productionTip = false;
Vue.config.devtools = true;

Vue.use(ElementUI);
Vue.use(VueRouter);
Vue.use(Components);
Vue.use(Plugins);
Vue.component('qrcode', QrcodeVue);

const router = new VueRouter({
  mode: 'history',
  routes: ROUTERS
});
Object.defineProperty(Vue.prototype, '$back', {value: () => router.back()});

router.beforeEach((to, from, next) => {
  if (to.meta.oauth) {
    next();
    return;
  }
  if (to.name === 'ControlPanel_Login') {
    UserUtil.clean();
  }

  const token = UserUtil.getAccessToken();
  if (token === null && to.name !== 'ControlPanel_Login') {
    next({
      name: 'ControlPanel_Login'
    });
  } else {
    next();
  }
});

try {
  const menus = MenuUtil.get();

  if (menus) {
    const routes = [] as RouteConfig[];
    MenuUtil.format(routes, menus);
    router.addRoutes(routes);
  }
} catch (e) {
  // 本地路由表解析失败
}

new Vue({
  router,
  store,
  render: (h) => h(App)
}).$mount('#app');
